package remoteControl.panel;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
 


public class ConfiguracionAPP extends Activity  implements SeekBar.OnSeekBarChangeListener {
    SeekBar mSeekBar;
    TextView mProgressText;

    BluetoothAdapter btAdapter;
    BluetoothSocket btSocket;
    public BluetoothDevice device;
    Button setMac;
    Button setSpeedMotor;
    Button getDataSD;
    EditText te;
    String macAdd;
    String message;
    private OutputStream out; 


    
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	

        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.config);
 

        
        setMac = (Button) findViewById(R.id.button1);
        setMac.setOnClickListener(setMacListener);
        
        setSpeedMotor = (Button) findViewById(R.id.button2);
        setSpeedMotor.setOnClickListener(setSpeedMotorListener);
        
        getDataSD = (Button) findViewById(R.id.button3);
        getDataSD.setOnClickListener(getDataSDListener);
        
        te = (EditText) findViewById(R.id.editText1);
        
        
        mSeekBar = (SeekBar)findViewById(R.id.seek);
        mSeekBar.setOnSeekBarChangeListener(this);
        mProgressText = (TextView)findViewById(R.id.progress);
        
        final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        String btAdress = "00:06:66:07:AC:2A";
        Bundle extras = getIntent().getExtras();
        if( extras != null)
        { 
         btAdress = extras.getString("MAC").toString();
        }
        
        te.setText(btAdress.toString());
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        device = btAdapter.getRemoteDevice(btAdress);
        
        try 
        {
         btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
         btSocket.connect();
        } 
        catch (IOException e) 
        {
         Toast.makeText(getApplicationContext(), "Could not connect socket", Toast.LENGTH_LONG).show();
        }

        
    }
 
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
        mProgressText.setText("Velocidad Motores: " + progress);
 
    }
 
    public void onStartTrackingTouch(SeekBar seekBar) {

    }
 
    public void onStopTrackingTouch(SeekBar seekBar) {

    }


     
     private Button.OnClickListener setMacListener = new Button.OnClickListener() 
     {
      public void onClick(View v) 
      {
       // Pasar a la ventana, enviado informacion
    	  Intent nextScreen = new Intent(getApplicationContext(), RemoteControlActivity.class);
    	  nextScreen.putExtra("MAC",te.getText().toString());
    	  startActivity(nextScreen);
      }
      };
      
      private Button.OnClickListener setSpeedMotorListener = new Button.OnClickListener() 
      {
       public void onClick(View v) 
       {
     	 try 
       	 {
    	  out = btSocket.getOutputStream();
       	 } 
       	 catch (IOException e) 
       	 {
          Toast.makeText(getApplicationContext(), "Could not listen data", Toast.LENGTH_LONG).show();
       	 }
         try 
         {
          int position = 9;
     	  out.write(position);	
     	  out.flush();
          out.write(mSeekBar.getProgress());
      	 
    	 } 
         catch (IOException e) 
         {
          Toast.makeText(getApplicationContext(), "Could not send data", Toast.LENGTH_LONG).show();
    	 }
       }
       };

       
       private Button.OnClickListener getDataSDListener = new Button.OnClickListener() 
       {
        public void onClick(View v) 
        {
        try {
        	out = btSocket.getOutputStream();
        	out.write(10);
			
		} 
        catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

       	
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        try 
        {
         InputStream instream = btSocket.getInputStream();
         int bytesRead =- 1;
         while (true) 
         {
            bytesRead = instream.read(buffer);
            message = message + new String(buffer, 0, bytesRead);
            break;
         }
         message = message.replace("null","");
         Toast.makeText(getApplicationContext(),message, Toast.LENGTH_LONG).show();
         }
        catch (IOException e) {Toast.makeText(getApplicationContext(), "Could not listen socket", Toast.LENGTH_LONG).show();}

        try
        {
            File ruta_sd = Environment.getExternalStorageDirectory();
         
            File f = new File(ruta_sd.getAbsolutePath(), "final_gps.txt");
         
            OutputStreamWriter fout =
                new OutputStreamWriter(
                    new FileOutputStream(f));
         
            fout.write(message);
            fout.close();
        }
        catch (Exception ex)
        {
            Log.e("Ficheros", "Error al escribir fichero a tarjeta SD");
        }
        }
        };
      
       
        @Override
    	protected void onDestroy() {
    		// TODO Auto-generated method stub
    		super.onDestroy();
    		try {
    			btSocket.close();
    			finish();
    		} catch (IOException e) {
    		}
    	}

    @Override
    protected void onStop() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	try {
    		btSocket.close();
    		finish();
    	} catch (IOException e) {
    	}
    }
 

}